package com.gyh.stlserver.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gyh.stlserver.entity.Admin;
import com.gyh.stlserver.mapper.AdminMapper;
import com.gyh.stlserver.service.AdminService;
import com.gyh.stlserver.util.PasswordUtil;
import com.gyh.stlserver.vo.AdminVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    private AdminMapper adminMapper;
    @Override
    public Admin getAdminByPhone(String phone) {
        return adminMapper.selectAdminByPhone(phone);
    }

    @Override
    public List<Admin> getAdminAll(Admin admin) {
        return adminMapper.select(admin);
    }

    @Override
    public PageInfo<Admin> getAdminByPage(Integer page, Integer limit, Admin admin) {
        if (ObjectUtil.isEmpty(page)) page=1;
        if (ObjectUtil.isEmpty(limit)) page=10;
        PageHelper.startPage(page,limit);
        List<Admin> admins = adminMapper.select(admin);
        return new PageInfo<>(admins);
    }

    @Override
    public int addAdmin(Admin admin) {
        /*加密*/
        admin.setPassword(PasswordUtil.md5encryption(admin.getPassword()));
        return adminMapper.insert(admin);
    }

    @Override
    public Admin checkPhone(String phone) {
        return adminMapper.selectAdminByPhone(phone);
    }

    @Override
    public int modifyAdmin(Admin admin) {

        admin.setPassword(PasswordUtil.md5encryption(admin.getPassword()));
        return adminMapper.update(admin);
    }

    @Override
    public int deleteAdmin(Integer id) {
        if (id==1){
            throw new RuntimeException("不能删除管理员");
        }
        return adminMapper.deleteAdmin(id);
    }

    @Override
    public int delSelected(Integer[] ids) {
        return adminMapper.deleteByIds(ids);
    }

    @Override
    public Admin login(AdminVo adminVo) {
        /*校验手机号*/
        boolean b = adminVo.getPhone().matches("^1[3-9]\\d{9}$");
        if (!b){
            throw new RuntimeException("手机号格式错误");
        }
        adminVo.setPassword(PasswordUtil.md5encryption(adminVo.getPassword()));
        return adminMapper.selectAdminByPhoneAndPwd(adminVo);
    }
}
